import React, { useState } from 'react';
import { Button, message, Spin } from 'antd';
import { SyncOutlined } from '@ant-design/icons';
import { useMeituanData } from '../hooks/useMeituanData';
import { useErrorHandler } from '../services/errorHandler';

/**
 * 同步按钮组件
 * 用于同步美团订单数据
 */
const SyncButton = ({
  storeId,
  groupId,
  type = 'button', // button | icon | text
  size = 'middle',
  onSuccess,
  onError,
  ...props
}) => {
  const [loading, setLoading] = useState(false);
  const { syncOrders } = useMeituanData();
  const { execute } = useErrorHandler();

  // 处理同步
  const handleSync = async () => {
    try {
      setLoading(true);
      
      const params = {};
      if (storeId) params.store_id = storeId;
      if (groupId) params.group_id = groupId;

      const result = await execute(() => syncOrders(params));
      
      if (result > 0) {
        message.success(`同步成功，新增 ${result} 条订单`);
      } else {
        message.info('暂无新订单');
      }
      
      onSuccess?.(result);
    } catch (error) {
      console.error('同步失败:', error);
      onError?.(error);
    } finally {
      setLoading(false);
    }
  };

  // 根据类型渲染不同的按钮样式
  const renderButton = () => {
    switch (type) {
      case 'icon':
        return (
          <Button
            type="text"
            icon={<SyncOutlined spin={loading} />}
            onClick={handleSync}
            loading={loading}
            size={size}
            {...props}
          />
        );

      case 'text':
        return (
          <a
            onClick={handleSync}
            style={{ 
              color: loading ? '#ccc' : undefined,
              cursor: loading ? 'not-allowed' : 'pointer'
            }}
            {...props}
          >
            {loading ? <Spin size="small" /> : '同步'}
          </a>
        );

      case 'button':
      default:
        return (
          <Button
            type="primary"
            icon={<SyncOutlined />}
            onClick={handleSync}
            loading={loading}
            size={size}
            {...props}
          >
            同步订单
          </Button>
        );
    }
  };

  return renderButton();
};

export default SyncButton;